package com.pucheng.bracelet.ui.fragment.home

import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.core.app.JobIntentService.enqueueWork
import androidx.lifecycle.Observer
import com.clj.fastble.BleManager
import com.clj.fastble.scan.BleScanRuleConfig
import com.gyf.barlibrary.ImmersionBar
import com.gyf.immersionbar.components.ImmersionFragment
import com.gyf.immersionbar.ktx.immersionBar
import com.pucheng.bracelet.R
import com.pucheng.bracelet.app.App
import com.pucheng.bracelet.app.service.SyncDataService
import com.pucheng.bracelet.app.util.ByteUtils
import com.pucheng.bracelet.app.util.StatusBarUtil
import com.pucheng.bracelet.databinding.FragmentHomeBinding
import com.pucheng.bracelet.ui.activity.blood_pressure.BloodPressureActivity
import com.pucheng.bracelet.ui.activity.gpsrun.RunStatisticsActivity
import com.pucheng.bracelet.ui.activity.heartrate.AllDayHeartRateActivity
import com.pucheng.bracelet.ui.activity.heartrate.HertRateActivity
import com.pucheng.bracelet.ui.activity.sao2.Sao2Activity
import com.pucheng.bracelet.ui.activity.sleep.SleepActivity
import com.pucheng.bracelet.ui.activity.steps.StepsActivity
import com.pucheng.bracelet.ui.activity.watch.WatchScanActivity
import com.pucheng.bracelet.viewmodel.home.HomeViewModel
import kotlinx.android.synthetic.main.fragment_home.*
import kotlinx.android.synthetic.main.layout_sao2_vaue_progress.*
import me.hgj.jetpackmvvm.demo.app.base.BaseFragment
import me.hgj.jetpackmvvm.ext.util.toJson


class HomeFragment : BaseFragment<HomeViewModel, FragmentHomeBinding>() {


    override fun layoutId() = R.layout.fragment_home
    override fun initView(savedInstanceState: Bundle?) {

//        StatusBarUtil.setColor(mActivity, resources.getColor(R.color.white), 10)
//        StatusBarUtil.setDarkMode(mActivity)
        mDatabind.vm = mViewModel
        mDatabind.appVM = appViewModel
        mDatabind.click = ProxyClick()

        BleManager.getInstance().init(App.instance)
        BleManager.getInstance()
            .enableLog(true)
            .setReConnectCount(1, 5000)
            .setConnectOverTime(20000).operateTimeout = 5000
//        val uuids =
//            arrayOf(UUID.fromString(UuidUtils.uuid16To128("FEEE")))
        val scanRuleConfig = BleScanRuleConfig.Builder()
//            .setServiceUuids(uuids)
//            .setDeviceName(true, "I691")
//            .setDeviceMac(mac)
            .setAutoConnect(true)
            .setScanTimeOut(100000)
            .build()
        BleManager.getInstance().initScanRule(scanRuleConfig)
        if (!BleManager.getInstance().isBlueEnable) {
            onEnableBluetoothClicked()
        }
    }

    fun onEnableBluetoothClicked() {
        val enableIntent =
            Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
        startActivity(enableIntent)
    }

    override fun dismissLoading() {
    }

//    override fun initImmersionBar() {
////        immersionBar {
////            statusBarColor(R.color.white)
////            navigationBarColor(R.color.colorPrimary)
////        }
//        ImmersionBar.with(this).statusBarColor(R.color.white).statusBarDarkFont(true)
//    }

    override fun lazyLoadData() {
        if (appViewModel.watchInfo.value != null && !TextUtils.isEmpty(appViewModel.watchInfo.value!!.mac)) {
            mViewModel.connectBle(appViewModel.watchInfo.value!!.mac)
        }
    }

    override fun showLoading(message: String) {
    }

    @SuppressLint("SetTextI18n")
    override fun createObserver() {
        appViewModel.bleConnectStatus.observe(viewLifecycleOwner,
            Observer {
                if (it) {
                    mViewModel.setLanguage()
                }
            })
        mViewModel.apply {
            //支持的功能
            supportFunction.observe(
                viewLifecycleOwner,
                Observer {
                    if (it != 0xff) {
                        cd_steps.visibility = if (ByteUtils.getIntToIAsBit(it, 0)) {
                            View.VISIBLE
                        } else {
                            View.GONE
                        }
                        cd_hr.visibility = if (ByteUtils.getIntToIAsBit(it, 1)) {
                            View.VISIBLE
                        } else {
                            View.GONE
                        }
                        cd_gps.visibility = if (ByteUtils.getIntToIAsBit(it, 2)) {
                            View.VISIBLE
                        } else {
                            View.GONE
                        }
                        cd_sao2.visibility = if (ByteUtils.getIntToIAsBit(it, 3)) {
                            View.VISIBLE
                        } else {
                            View.GONE
                        }
                        cd_bp.visibility = if (ByteUtils.getIntToIAsBit(it, 4)) {
                            View.VISIBLE
                        } else {
                            View.GONE
                        }

                    }
                })

            batteryStatus.observe(
                viewLifecycleOwner,
                Observer { appViewModel.batteryStatus.value = it })
            bleConnectStatus.observe(
                viewLifecycleOwner,
                Observer {
                    appViewModel.bleConnectStatus.value = it
//                    SyncDataService.enqueueWork(
//                        mActivity,
//                        SyncDataService::class.java, 1, Intent()
//                    )
                })
            sao2Data.observe(
                viewLifecycleOwner,
                Observer {
                    tv_sao2_vaue.text = "${it.name}"
                    tv_sao2_date.text = it.measuredDate
                    pb_sao2.progress = (it.sao2Vaule - 80) * 5
                    mActivity.startService(Intent(mActivity, SyncDataService::class.java))
                })

            hertRateData.observe(
                viewLifecycleOwner,
                Observer {
                    tv_hr.text = "${it.name}BMP"
                    tv_hr_date.text = it.measuredDate
                })

            bpInfo.observe(
                viewLifecycleOwner,
                Observer {
                    tv_bp_vaue.text = "${it.name}MMHG"
                    tv_bp_date.text = it.measuredDate

                })
            sleepDataInfo.observe(viewLifecycleOwner, Observer {
                if (it != null) {
                    sleepData.value = it
                }
            })
            if (sleepData.value == null) {
                sleepTo7Day.observe(viewLifecycleOwner, Observer {
                    if (!it.isNullOrEmpty()) {
                        sleepData.value = it.first()
                    }
                })
            }
            sleepData.observe(viewLifecycleOwner, Observer {
                if (it != null) {
                    sleep_info.setSleepInfo(it)
                }
            })
        }

    }

    inner class ProxyClick {
        /**步数**/
        fun toSteps() {
            startActivity(Intent(mActivity, StepsActivity::class.java))
        }

        /**睡眠**/
        fun toSleep() {
            startActivity(Intent(mActivity, SleepActivity::class.java))
        }

        /**全天心率**/
        fun toAllDayHr() {
            startActivity(Intent(mActivity, AllDayHeartRateActivity::class.java))
        }

        /**心率**/
        fun toHr() {
            startActivity(Intent(mActivity, HertRateActivity::class.java))
        }

        /**血压**/
        fun tobp() {
            startActivity(Intent(mActivity, BloodPressureActivity::class.java))
        }

        /**血氧饱和度**/
        fun toSao2() {
            startActivity(Intent(mActivity, Sao2Activity::class.java))
        }

        /**GPS跑步**/
        fun toRunStatistics() {
            startActivity(Intent(mActivity, RunStatisticsActivity::class.java))
        }

        /**连接手环**/
        fun onConnectWatch() {
            startActivity(Intent(mActivity, WatchScanActivity::class.java))
        }
    }

    override fun onResume() {
        super.onResume()
        mViewModel.setLanguage()
    }

}

